package com.carbohydrate42.kotlin_compose_demo.compose

import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Environment
import android.provider.MediaStore
import android.util.Log
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.result.launch
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.material3.Button
import androidx.compose.material3.Divider
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.core.content.FileProvider
import com.carbohydrate42.kotlin_compose_demo.BuildConfig
import java.io.File
import java.util.Date


private fun getStorageFileUri(
    filePrefix: String,
    fileSuffix: String,
    context: Context
): Uri {
    val storageFile: File? =
        if (Environment.MEDIA_MOUNTED == Environment.getExternalStorageState()) {
            context.externalCacheDir
        } else {
            context.cacheDir
        }


    // 暂时只是存在 app 自身的缓存下目录下的
    // 参考 android 应用文件目录
    // https://developer.android.com/training/data-storage/app-specific?hl=zh-cn
    val photoFile = File.createTempFile(
        filePrefix,
        fileSuffix,
        storageFile
    ).apply {
        createNewFile()
        deleteOnExit()
    }

    return FileProvider.getUriForFile(context, "${BuildConfig.APPLICATION_ID}.provider", photoFile)
}


private class MyCaptureVideo : ActivityResultContracts.CaptureVideo() {
    override fun createIntent(context: Context, input: Uri): Intent {
        return super.createIntent(context, input)
            .putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1)
            .putExtra(MediaStore.EXTRA_DURATION_LIMIT, 15)
    }
}


/**
 * 参考 拍视频是模仿拍照写的
 * https://juejin.cn/post/7082314521284444173
 */
@Preview(showBackground = true, showSystemUi = true)
@Composable
fun TakePictureAndVideo() {

    val context = LocalContext.current

    var picturePreview by remember { mutableStateOf<Bitmap?>(null) }

    val takePicturePreview =
        rememberLauncherForActivityResult(ActivityResultContracts.TakePicturePreview()) {
            picturePreview = it
        }

    val takePicture =
        rememberLauncherForActivityResult(ActivityResultContracts.TakePicture()) {
            Log.d("TakePicture", "takePicture: $it")
        }


    val captureVideo =
        rememberLauncherForActivityResult(MyCaptureVideo()) {
            Log.d("CaptureVideo", "captureVideo: $it")
        }


    Column {
        Button(onClick = {
            takePicturePreview.launch()
        }) {
            Text(text = "调用系统拍照并预览")
        }

        picturePreview?.asImageBitmap()?.let {
            Image(
                bitmap = it,
                contentDescription = "图片预览",
                modifier = Modifier
                    .height(200.dp)
                    .fillMaxWidth()
            )
        }

        Divider()


        Button(onClick = {
            takePicture.launch(
                getStorageFileUri(
                    "capture_picture_${Date().time}",
                    ".png",
                    context
                )
            )
        }) {
            Text(text = "调用系统拍照片, 并缓存在 app 的缓存目录下")
        }

        Divider()

        Button(onClick = {
            captureVideo.launch(
                getStorageFileUri(
                    "capture_video_${Date().time}",
                    ".mp4",
                    context
                )
            )
        }) {
            Text(text = "调用系统拍视频, 并缓存在 app 的缓存目录下")
        }


        Divider()


    }
}